<script lang="ts" setup>
import { useVbenModal } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { getLinkage } from '#/api/portal/linkage';
import { postLinkageData, putLinkageData } from '#/api/portal/linkageData';

const cascaders: any = ref([]);

const [Form, formApi] = useVbenForm({
  handleSubmit: onSubmit,
  schema: [
    {
      component: 'Input',
      dependencies: {
        show: false,
        // 随意一个字段改变时，都会触发
        triggerFields: ['id'],
      },
      fieldName: 'id',
      label: 'ID',
    },
    {
      component: 'Input',
      dependencies: {
        show: false,
        // 随意一个字段改变时，都会触发
        triggerFields: ['linkage_id'],
      },
      fieldName: 'linkage_id',
      label: 'linkage_id',
    },
    {
      component: 'Input',
      dependencies: {
        show: false,
        // 随意一个字段改变时，都会触发
        triggerFields: ['parent_id'],
      },
      fieldName: 'parent_id',
      label: 'parent_id',
    },
    {
      component: 'Input',
      dependencies: {
        trigger: (values, form) => {
          form.setFieldValue('code', values.name);
        },
        // 随意一个属性改变时，都会触发
        triggerFields: ['name', 'id', 'code'],
      },
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'name',
      label: '名称',
      rules: 'required',
    },
    {
      component: 'Input',
      dependencies: {
        show: false,
        // 随意一个属性改变时，都会触发
        triggerFields: ['name', 'id', 'code'],
      },
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'code',
      label: '值',
    },
    {
      component: 'Switch',
      defaultValue: 1,
      componentProps: {
        checkedValue: 1,
        unCheckedValue: 0,
        checkedChildren: '是',
        unCheckedChildren: '否',
      },
      fieldName: 'status',
      label: '状态',
    },
  ],
  showDefaultActions: false,
});

const [Modal, formModalApi] = useVbenModal({
  fullscreenButton: false,
  onConfirm: async () => {
    await formApi.validateAndSubmitForm();
  },
  async onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const values: any = formModalApi.getData();

      if (values.form) {
        formApi.setValues(values.form);
      } else {
        formApi.setFieldValue('linkage_id', values.linkage_id);
      }
      const {
        data: { list },
      } = await getLinkage();
      cascaders.value = list;
    }
  },
});

async function onSubmit(values: any) {
  function showMsg(msg: string) {
    message.success(msg);
    formModalApi.setData({ isUpdata: true });
    formModalApi.close();
  }
  if (values.id) {
    const { msg } = await putLinkageData(values.id, values);
    showMsg(msg);
  } else {
    const { msg } = await postLinkageData(values);
    showMsg(msg);
  }
}
</script>
<template>
  <Modal>
    <Form />
  </Modal>
</template>

<style lang="scss" scoped></style>
